#include <iostream>
#include <sstream>
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>

void serialize()
{
    const char *name = "张三";
    int age = 20;
    float score[] = {77.5, 88, 99.5};
    Json::Value val;
    val["姓名"] = name;
    val["年龄"] = age;
    val["成绩"].append(score[0]);
    val["成绩"].append(score[1]);
    val["成绩"].append(score[2]);
    Json::StreamWriterBuilder swb;
    swb.settings_["emitUTF8"] = true;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    std::stringstream ss;
    int ret = sw->write(val, &ss);
    if (ret != 0)
    {
        std::cout << "write failed!" << std::endl;
        return;
    }

    std::cout << ss.str() << std::endl;
}

void unserialize()
{
    std::string str = R"({"姓名":"小明", "年龄":18, "成绩":[76.5, 55, 88]})";
    Json::Value val;
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    std::string err;
    bool ret = cr->parse(str.c_str(), str.c_str() + str.size(), &val, &err);
    if (!ret)
    {
        std::cout << "parse failed: " << err.c_str() << std::endl;
        return;
    }

    std::cout << "姓名: " << val["姓名"].asString() << std::endl;
    std::cout << "年龄: " << val["年龄"].asInt() << std::endl;
    std::cout << "成绩: ";
    for (int i = 0; i < val.size(); ++i)
    {
        std::cout << val["成绩"][i].asFloat() << " ";
    }
    std::cout << std::endl;
}

int main()
{
    serialize();
    unserialize();

    return 0;
}